/**
 * SceneIntro
 * 	@brief  Shows pictures fading in and out
 * 	@author Bruno Miguel de Oliveira Tamer <bmotamer@gmail.com>
 */

using UnityEngine;

public class SceneIntro : MonoBehaviour
{
	
	public  Texture2D[] Textures;
	public  string 	    NextLevel;
	public  float       PreDelay;
	public  float 	    PosDelay;
	public  float 	    FadeOutSpeed;
	public  float 	    MidDelay;
	public  float 	    FadeInSpeed;
	private int         _Index;
	private float       _Timer;
	private bool        _Flag;
	private float       _Alpha;
	
	public void Start()
	{
		QualitySettings.vSyncCount = 1;
		if (
			(Textures.Length == 0) ||
			((_Index = FindNextIndex(-1)) == Textures.Length)
		)
			Application.LoadLevel(NextLevel);
		else
		{
			_Timer   = PreDelay;
			FadeInSpeed  = Mathf.Clamp(FadeInSpeed,  0.0f, 1.0f);
			FadeOutSpeed = Mathf.Clamp(FadeOutSpeed, 0.0f, 1.0f);
		}
	}
	
	public void Update()
	{
		float smoothDeltaTime = Mathf.Clamp(Time.smoothDeltaTime, 0.01666667f, float.MaxValue);
		if (_Timer > 0.0f)
			_Timer = Input.anyKeyDown ? 0.0f : Mathf.Clamp(_Timer - smoothDeltaTime, 0.0f, float.MaxValue);
		else if (_Index == Textures.Length)
			if (string.IsNullOrEmpty(NextLevel))
				Application.Quit();
			else
				Application.LoadLevel(NextLevel);
		else if (_Flag)
		{
			_Alpha = Mathf.Clamp(_Alpha - FadeOutSpeed * smoothDeltaTime, 0.0f, 1.0f);
			if (_Alpha == 0.0f)
			{
				_Index = FindNextIndex(_Index);
				_Timer = PosDelay;
				if (_Index < Textures.Length)
					_Timer += PreDelay;
				_Flag = false;
			}
		}
		else
		{
			_Alpha = Mathf.Clamp(_Alpha + FadeInSpeed * smoothDeltaTime, 0.0f, 1.0f);
			if (_Alpha == 1.0f)
			{
				_Timer = MidDelay;
				_Flag  = true;
			}
		}
	}
	
	public void OnGUI()
	{
		if (_Index == Textures.Length)
			return;
		Matrix4x4 tempMatrix = GUI.matrix;
		Color     tempColor  = GUI.color;
		Texture2D texture 	 = Textures[_Index];
		Vector3   scale      = new Vector3(Screen.width / 1024.0f, Screen.height / 512.0f, 1.0f);
		Vector3   position   = new Vector3(0.5f * (Screen.width - scale.x * texture.width), 0.5f * (Screen.height - scale.y * texture.height), 0.0f);
		GUI.matrix = Matrix4x4.TRS(position, Quaternion.identity, scale);
		GUI.color  = Color.white * _Alpha;
		GUI.DrawTexture(new Rect(0.0f, 0.0f, texture.width, texture.height), texture);
		GUI.color  = tempColor;
		GUI.matrix = tempMatrix;
	}
	
	protected int FindNextIndex(int currentIndex)
	{
		if (currentIndex == int.MaxValue)
			return Textures.Length;
		for (
			int nextIndex = currentIndex + 1;
			nextIndex < Textures.Length;
			nextIndex++
		)
			if (Textures[nextIndex] != null)
				return nextIndex;
		return Textures.Length;
	}
	
}